package com.baidu.util.time.nlp.festival.strategy;

import com.baidu.util.time.nlp.festival.FestivalDayInfo;
import com.baidu.util.time.nlp.festival.Lunar;
import com.baidu.util.time.nlp.festival.LunarSolarConverter;
import com.baidu.util.time.nlp.festival.Solar;
import com.baidu.util.time.util.DateUtil;
import org.joda.time.DateTime;

/**
 * 农历节日
 */
public class LunarFestivalDayStrategy implements FestivalDayStrategy {
    private boolean isAutoPlusYear = false;

    @Override
    public DateTime getDateTime(String text, DateTime baseTime, FestivalDayInfo info) {
        if (text.indexOf(info.getName()) == -1) {
            return null;
        }
        if (baseTime == null) {
            isAutoPlusYear = true;
            baseTime = DateTime.now();
        }

        DateTime festivalDay = toSolar(baseTime.getYear(), info);

        if (isAutoPlusYear && baseTime.isAfter(festivalDay)) {
            festivalDay = toSolar(baseTime.plusYears(1).getYear(), info);
        }
        return festivalDay;
    }

    /**
     * 转换公历日期
     *
     * @param resultYear
     * @param info
     * @return
     */
    private DateTime toSolar(int resultYear, FestivalDayInfo info) {
        String[] dateArray = info.getDateString().split("-");
        Lunar lunar = new Lunar();
        lunar.lunarYear = resultYear;
        lunar.lunarMonth = Integer.parseInt(dateArray[0]);
        lunar.lunarDay = Integer.parseInt(dateArray[1]);
        Solar solar = LunarSolarConverter.LunarToSolar(lunar);
        DateTime festivalDay = new DateTime(solar.solarYear, solar.solarMonth, solar.solarDay, 0, 0);
        return DateUtil.setDefaultTime(festivalDay);
    }
}
